package org.androidnotebook;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class PageDbAdapter {
	public static final String KEY_ID = "_id";
	public static final String KEY_BOOKID = "bookid";
	public static final String KEY_TITLE = "title";
	public static final String KEY_WEIGHT = "weight";
	public static final String KEY_BODY = "body";

	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	private static final String DATABASE_NAME = "notebook";
	private static final String DATABASE_TABLE = "page";
	private static final int DATABASE_VERSION = 2;
	private static final int WEIGHT_GAP = 100;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		
		@Override
		public void onCreate(SQLiteDatabase db) {
			// Nothing To Do here as it was done in BookDBAdapter
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// Nothing To Do here as it was done in BookDBAdapter
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public PageDbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the notebook database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public PageDbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * Create a new page using the title provided. If the page is successfully
	 * created return the new rowId for that page, otherwise return a -1 to
	 * indicate failure.
	 * 
	 * @param title
	 *            the title of the page
	 * @param bookId
	 * 	           the id of the book to create the page in
	 * @return rowId or -1 if failed
	 */
	public long createPage(String title,long bookId) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_TITLE, title);
		initialValues.put(KEY_BOOKID, bookId);

		int weight = WEIGHT_GAP;
		Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] { "max("
				+ KEY_WEIGHT + ")" }, null, null, null, null, null, null);

		if (mCursor != null && mCursor.moveToFirst()) {
			weight = mCursor.getInt(0) + WEIGHT_GAP;
		}

		initialValues.put(KEY_WEIGHT, weight);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Delete all pages for a given bookId
	 * 
	 * @param bookId
	 *            id of book pages to delete
	 * @return true if deleted, false otherwise
	 */
	public boolean deletePagesforBook(long bookId) {

		return mDb.delete(DATABASE_TABLE, KEY_BOOKID + "=" + bookId, null) > 0;
	}

	/**
	 * Delete the page with the given rowId
	 * 
	 * @param rowId
	 *            id of page to delete
	 * @return true if deleted, false otherwise
	 */
	public boolean deletePage(long rowId) {

		return mDb.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all pages in the database
	 * 
	 * @param bookId
	 *            the id of the book from which to get the pages from
	 * @return Cursor over all pages
	 */
	public Cursor fetchAllPagesforBook(long bookId) {

		return mDb.query(DATABASE_TABLE, new String[] { KEY_ID, KEY_TITLE },
				KEY_BOOKID + "=" + Long.toString(bookId), null, null, null,
				null);
	}

	/**
	 * Return a Cursor positioned at the page that matches the given rowId
	 * 
	 * @param rowId
	 *            id of page to retrieve
	 * @return Cursor positioned to matching page, if found
	 * @throws SQLException
	 *             if page could not be found/retrieved
	 */
	public Cursor fetchPage(long rowId) throws SQLException {

		Cursor mCursor =

		mDb.query(true, DATABASE_TABLE, new String[] { KEY_ID, KEY_TITLE, KEY_BODY },
				KEY_ID + "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;

	}

	/**
	 * Update the page title using the details provided. The page to be updated is
	 * specified using the rowId, and it is altered to use the title value
	 * passed in
	 * 
	 * @param rowId
	 *            id of page to update
	 * @param title
	 *            value to set page title to
	 * @return true if the page was successfully updated, false otherwise
	 */
	public boolean updatePageTitle(long rowId, String title) {
		ContentValues args = new ContentValues();
		args.put(KEY_TITLE, title);

		return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
	}

	/**
	 * Update the page body using the details provided. The page to be updated is
	 * specified using the rowId, and it is altered to use the body value
	 * passed in
	 * 
	 * @param rowId
	 *            id of page to update
	 * @param body
	 *            value to set page body to
	 * @return true if the page was successfully updated, false otherwise
	 */
	public boolean updatePageBody(long rowId, String body) {
		ContentValues args = new ContentValues();
		args.put(KEY_BODY, body);

		return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
	}
}
